<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chat Interface</title>
    <link href="./assistant.css" rel="stylesheet">
    <!-- 添加 Marked.js 用于解析 Markdown -->
    <script src="./marked.min.js"></script>
    <!-- 添加 highlight.js 用于代码高亮 -->
    <script src="./highlight.min.js"></script>
    <style>
        .typing-animation span {
            animation: typing 1s infinite;
            display: inline-block;
            margin: 0 1px;
        }
        .typing-animation span:nth-child(2) {
            animation-delay: 0.2s;
        }
        .typing-animation span:nth-child(3) {
            animation-delay: 0.4s;
        }
        @keyframes typing {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
        }
        /* Markdown 样式 */
        .markdown-body {
            line-height: 1.6;
        }
        .markdown-body p {
            margin-bottom: 0.5em;
        }
        .markdown-body pre {
            background-color: #f6f8fa;
            border-radius: 6px;
            padding: 16px;
            margin: 8px 0;
        }
        .markdown-body code {
            font-family: monospace;
            padding: 2px 4px;
            background-color: #f6f8fa;
            border-radius: 4px;
        }
        .markdown-body pre code {
            padding: 0;
            background-color: transparent;
        }
        
        /* 自定义滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c5c5c5;
            border-radius: 10px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        /* 聊天气泡动画 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .message-animation {
            animation: fadeIn 0.3s ease-out forwards;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen">
    <div class="container mx-auto p-4 max-w-4xl">
        <!-- Header -->
        <div class="flex justify-between items-center mb-6 bg-white rounded-xl shadow-md p-4">
            <div class="flex items-center">
                <div class="w-10 h-10 rounded-full bg-blue-600 flex items-center justify-center text-white mr-3">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
                    </svg>
                </div>
                <h1 class="text-2xl font-bold text-gray-800">AI聊天助手</h1>
            </div>
            <button id="newChatBtn" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition-colors shadow-md flex items-center">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                创建新对话
            </button>
        </div>

        <!-- Chat Container -->
        <div id="chatContainer" class="bg-white rounded-xl shadow-lg p-6 mb-4 h-[500px] overflow-y-auto">
            <div id="messageList" class="space-y-6">
                <!-- Messages will be inserted here -->
                <div class="flex items-center justify-center h-full text-gray-400">
                    <div class="text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 mx-auto mb-4 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                        </svg>
                        <p class="text-lg font-medium">开始一段新的对话</p>
                        <p class="mt-1">输入消息，开始与AI助手交流</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Input Area -->
        <div class="bg-white rounded-xl shadow-md p-4">
            <textarea id="userInput" 
                class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none mb-3"
                placeholder="输入消息..." rows="3"></textarea>
            <div class="flex justify-end gap-3">
                <button id="sendBtn" 
                    class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition-colors shadow-md flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                    </svg>
                    发送
                </button>
                <button id="stopBtn" 
                    class="bg-red-500 hover:bg-red-600 text-white px-6 py-2 rounded-lg transition-colors shadow-md hidden flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                    停止
                </button>
            </div>
        </div>
    </div>

    <script>
        // 获取当前页面的文件名
        const currentPage = window.location.pathname.split('/').pop() || 'chat.html';

        // 加载配置文件
        async function loadConfig() {
            try {
                const response = await fetch('config.json');
                const config = await response.json();
                return config;
            } catch (error) {
                console.error('Error loading config:', error);
                return null;
            }
        }

        let config;
        
        // DOM Elements
        const messageList = document.getElementById('messageList');
        const userInput = document.getElementById('userInput');
        const sendBtn = document.getElementById('sendBtn');
        const newChatBtn = document.getElementById('newChatBtn');
        let currentController = null;  // 用于存储当前的 AbortController

        // 配置 marked.js
        marked.setOptions({
            highlight: function(code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                }
                return hljs.highlightAuto(code).value;
            },
            breaks: true
        });

        // Helper function to create message elements
        function createMessageElement(content, isAI, isTyping = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `flex items-start space-x-3 ${isAI ? 'justify-start' : 'justify-end'} message-animation`;
            
            // 创建头像元素
            const avatar = document.createElement('div');
            if (isAI) {
                avatar.className = 'w-10 h-10 rounded-full bg-blue-600 flex items-center justify-center text-white flex-shrink-0 shadow-md';
                avatar.innerHTML = 'AI';
                messageDiv.appendChild(avatar);
            }

            const contentWrapper = document.createElement('div');
            contentWrapper.className = 'flex flex-col max-w-[75%]';

            const messageBubble = document.createElement('div');
            messageBubble.className = `rounded-2xl p-4 ${
                isAI ? 'bg-gray-100 text-gray-800 shadow-sm' : 'bg-blue-600 text-white shadow-md'
            }`;

            if (isTyping) {
                messageBubble.innerHTML = '<div class="typing-animation"><span>.</span><span>.</span><span>.</span></div>';
                messageBubble.classList.add('typing');
            } else {
                if (isAI) {
                    // 处理 Markdown
                    messageBubble.innerHTML = marked.parse(content);
                    messageBubble.classList.add('markdown-body');
                    // 代码高亮
                    messageBubble.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightBlock(block);
                    });
                } else {
                    messageBubble.textContent = content;
                }
            }
            
            contentWrapper.appendChild(messageBubble);
            
            // 添加时间戳
            const timestamp = document.createElement('div');
            const now = new Date();
            timestamp.textContent = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
            timestamp.className = 'text-xs text-gray-500 mt-1 ' + (isAI ? 'ml-1' : 'mr-1 text-right');
            contentWrapper.appendChild(timestamp);
            
            messageDiv.appendChild(contentWrapper);

            if (!isAI) {
                // 用户头像
                const userAvatar = document.createElement('div');
                userAvatar.className = 'w-10 h-10 rounded-full bg-green-500 flex items-center justify-center text-white flex-shrink-0 shadow-md';
                userAvatar.innerHTML = '我';
                messageDiv.appendChild(userAvatar);
            }
            
            return messageDiv;
        }

        // 初始化配置
        async function initialize() {
            config = await loadConfig();
            if (!config) {
                console.error('Failed to load configuration');
                return;
            }
        }

        // Send message function
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;
            
            // 清除欢迎消息
            if (messageList.querySelector('.text-center')) {
                messageList.innerHTML = '';
            }

            // Add user message to chat
            messageList.appendChild(createMessageElement(message, false));
            userInput.value = '';

            // 添加AI正在输入的提示
            const typingIndicator = createMessageElement('', true, true);
            messageList.appendChild(typingIndicator);

            // Scroll to bottom
            messageList.scrollTop = messageList.scrollHeight;

            try {
                const pageConfig = config.page_config[currentPage];
                const apiConfig = config.api_config[pageConfig.default_api];
                const promptConfig = config.system_prompts[pageConfig.default_prompt];

                // 创建新的 AbortController
                currentController = new AbortController();
                const signal = currentController.signal;

                // 显示停止按钮
                document.getElementById('stopBtn').classList.remove('hidden');
                document.getElementById('sendBtn').classList.add('hidden');

                // Call AI API with stream
                const response = await fetch(apiConfig.url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiConfig.api_key}`
                    },
                    body: JSON.stringify({
                        model: apiConfig.model,
                        messages: [
                            {
                                role: "system",
                                content: promptConfig.content
                            },
                            {
                                role: "user",
                                content: message
                            }
                        ],
                        stream: true
                    }),
                    signal  // 添加 signal 用于中断请求
                });

                // 创建新的消息元素用于显示AI回复
                const aiMessageElement = createMessageElement('', true);
                // 移除输入中的提示
                messageList.removeChild(typingIndicator);
                messageList.appendChild(aiMessageElement);

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let aiResponse = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    // 解码收到的数据
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ') && line !== 'data: [DONE]') {
                            try {
                                const data = JSON.parse(line.slice(6));
                                const content = data.choices[0]?.delta?.content || '';
                                aiResponse += content;
                                // 使用 marked 处理 Markdown
                                const markdownContent = marked.parse(aiResponse);
                                aiMessageElement.querySelector('.markdown-body').innerHTML = markdownContent;
                                // 应用代码高亮
                                aiMessageElement.querySelectorAll('pre code').forEach((block) => {
                                    hljs.highlightBlock(block);
                                });
                            } catch (e) {
                                console.error('Error parsing chunk:', e);
                            }
                        }
                    }
                    
                    // 自动滚动到底部
                    messageList.scrollTop = messageList.scrollHeight;
                }
            } catch (error) {
                if (error.name === 'AbortError') {
                    console.log('Fetch aborted');
                } else {
                    console.error('Error:', error);
                    // 移除输入中的提示
                    messageList.removeChild(typingIndicator);
                    messageList.appendChild(createMessageElement('抱歉，发生了错误，请稍后重试。', true));
                }
            } finally {
                // 隐藏停止按钮，显示发送按钮
                document.getElementById('stopBtn').classList.add('hidden');
                document.getElementById('sendBtn').classList.remove('hidden');
                currentController = null;
            }
        }

        // Event Listeners
        document.addEventListener('DOMContentLoaded', initialize);
        
        sendBtn.addEventListener('click', sendMessage);
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 停止按钮点击事件
        document.getElementById('stopBtn').addEventListener('click', () => {
            if (currentController) {
                currentController.abort();
            }
        });

        // New chat button
        newChatBtn.addEventListener('click', () => {
            messageList.innerHTML = `
                <div class="flex items-center justify-center h-full text-gray-400">
                    <div class="text-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 mx-auto mb-4 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                        </svg>
                        <p class="text-lg font-medium">开始一段新的对话</p>
                        <p class="mt-1">输入消息，开始与AI助手交流</p>
                    </div>
                </div>
            `;
        });
    </script>
</body>
</html>